<template>
  <div class="app-container">
    <u-page-config
      :filter-array="filterArray"
      v-model="filter"
      :actionBtn="actionBtn"
      label-width="100px"
      :getList="getList"
      :tableData="tableData"
      :tableColumn="tableColumn"
      :total="total"
      :loading="loading"
      @addRow="addRow"
      @editRow="editRow"
      @historyVersion="historyVersion"
    >

    </u-page-config>

    <el-dialog :title="title" :visible.sync="visible" width="600px" :close-on-click-modal="false">
      <u-form
        ref="uFormRef"
        label-width="134px"
        v-model="form"
        :defaultForm="defaultForm"
        :formArray="renderForm"
        :show-btn="false"
        @submit="onsubmit"
        @beforeUpload="beforeUpload"
        @close="visible = false"
        :mode="mode"

      >
      </u-form>
    </el-dialog>
    <el-dialog title="历史版本" :visible.sync="historyVisible" width="800" :close-on-click-modal="false">
      <history :pluginCode="pluginCode"/>
    </el-dialog>
  </div>
</template>

<script>
import UPageConfig from '@/components/uPageConfig/index'
import UForm from '@/components/uForm'
import History from './componets/history.vue'
import table from '@/mixin/uTable'
import Treeselect from '@riophae/vue-treeselect'
import {
  getBaseStepList,
  addStep,
  delStep,
  updateStep
} from '@/api/items/serviceSteps'
import { listPlugins, addPlugins, reqReleaseVersion } from '@/api/device/plugin.js'
import { getToken } from '../../../utils/auth'
import { Message } from 'element-ui'

export default {
  name: 'UpdatePlan',
  mixins: [table],
  dicts: ['step_type'],
  components: { UPageConfig, UForm, History },
  data() {
    return {
      filter: {
        pageSize: 10,
        pageNum: 1,
        data: {
          pluginName: ''
        }
      },
      filterArray: [
        { label: '插件名称', key: 'pluginName', type: 'input' }
      ],
      tableColumn: [
        { label: '插件名称', prop: 'pluginName' },
        { label: '插件图标', prop: 'iconUrl', type: 'image' },
        { label: '插件描述', prop: 'remark' },
        { label: '版本号', prop: 'version' },
        { label: '创建时间', prop: 'createTime', type: 'time', width: 200 },
        {
          label: '操作', type: 'btn', attr: { width: 180 }, btnArr: [
            {
              text: '历史版本',
              emit: 'historyVersion'
              // permissions: 'items:serviceSteps:edit',
            },
            {
              text: '发布新版本',
              emit: 'editRow'
              // permissions: 'items:serviceSteps:edit',
            }
          ]
        }
      ],
      actionBtn: [
        {
          type: 'primary',
          text: '新建',
          icon: 'el-icon-plus',
          emit: 'addRow',
          permissions: 'items:serviceSteps:add'
        }
      ],
      form: {},
      // 表单默认必填参数 重置表单时需要用到
      defaultForm: {},
      formArray: [
        {
          label: '插件名称: ', key: 'pluginName', col: 24, type: 'input',
          rule: { required: true, message: '插件名称不能为空！', trigger: 'blur' },
          group: '1'
        },
        // {
        //   label: "插件编码: ", key: "componentName", col: 24, type: "input",
        //   rule: {required: true, message: '步骤组件名称不能为空！', trigger: 'blur'},
        // },
        {
          label: '版本号: ', key: 'version', col: 24, type: 'input', placeholder: '请输入版本号：例：1.0.0',
          rule: { required: true, message: '版本号不可为空！', trigger: 'blur' },
          group: '1,2'
        },
        {
          label: '描述: ', key: 'remark', col: 24, type: 'textarea', placeholder: '请输入插件描述',
          group: '1,2'
        },

        {
          label: '插件图标: ',
          key: 'iconUrl',
          col: 24,
          type: 'upload',
          inputType: 'image',
          action: '/minio/upload',
          limit: 1,
          headers: {
            Authorization: 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
          },
          group: '1,2'
        },
        {
          label: '更新内容: ', key: 'updateContent', col: 24, type: 'textarea', placeholder: '请输入更新内容',
          group: '2'
        },
        {
          label: '文件', key: 'fileUrl', type: 'upload', fileList: [],
          headers: {
            Authorization: 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改

          },
          col: 24, inputType: 'file', action: '/minio/upload', placeholder: '请选择插件压缩包', limit: 1,
          group: '1,2',
          rule: { required: true, message: '请上传插件', trigger: 'blur' }
        }
      ],
      historyVisible: false,
      pluginCode: ''
    }
  },
  computed: {
    renderForm() {
      if (this.form.pluginId) {
        return this.formArray.filter(item => item.group.includes('2'))
      }
      return this.formArray.filter(item => item.group.includes('1'))
    }
  },
  watch: {
    visible(val) {
      if (!val) {
        this.formArray.forEach(item => {
          if (item.type === 'upload') {
            item.fileList = []
          }
        })
      }
    }
  },
  methods: {
    historyVersion({ pluginCode }) {
      this.pluginCode = pluginCode
      this.historyVisible = true
    },
    beforeUpload(key, file) {
      if (!this.form.pluginAppName) {
        if (key === 'fileUrl') {
          this.form.pluginAppName = file.name.replace(/\..+/, '')
        }
      }
    },

    async onsubmit(callback) {
      this.formArray.forEach(item => {
        if (item.key === 'fileUrl') {
          console.log(item)
        }
      })

      const form = JSON.parse(JSON.stringify(this.form))
      if (this.form.pluginId) {
        await reqReleaseVersion(form)
        Message.success('发布成功')
      } else {
        await addPlugins(form)
        Message.success('添加成功')
      }
      this.visible = false
      this.getList()
      this.form = {}
      callback()
    },
    // 添加
    addRow() {
      this.mode = 'form'
      this.title = '新增插件'
      this.visible = true
      this.formArray.forEach(item => {
        if (item.key === 'version') {
          item.placeholder = '请输入版本号：例：1.0.0'
        }
      })
    },
    editRow(row) {
      this.mode = 'form'
      this.title = '发布新版本'
      this.visible = true
      this.form = JSON.parse(JSON.stringify(row))
      this.form.fileUrl = ''

      this.formArray.forEach(item => {
        if (item.type === 'upload') {
          if (this.form[item.key]) {
            item.fileList = [
              { name: 'file', url: this.form[item.key] }
            ]
          }
        }

        if (item.key === 'version') {
          item.placeholder = this.form.version
        }
      })
      this.form.version = ''
    },

    // 添加文件上传成功、删除图片时都会被调用
    imageUploadChange(imgUrl) {
      this.form.pic = imgUrl
    },
    // 重写请求参数 因为这个接口参数是放在data里的
    getListRequestParams() {
      const params = {
        pageSize: this.filter.pageSize,
        pageNum: this.filter.pageNum,
        data: {
          ...this.filter.data
        }
      }
      return params
    },
    /** 查询工单列表 */
    async getList() {
      const res = await this.getInit(listPlugins, {})
      this.tableData = res.data.list
      this.total = res.data.total
    }
  }
}
</script>

<style lang="scss" scoped>
.form-item-wrap {
  display: flex;
}
</style>
